package com.spsoft.vatoutinv.jobHandler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.model.Result;
import com.spsoft.core.model.bo.TokenUser;
import com.spsoft.core.model.leqidmz.param.ApplyCreditParams;
import com.spsoft.core.model.leqidmz.param.BaseNsrRequestParams;
import com.spsoft.core.model.leqidmz.param.QueryClassifyCodeParams;
import com.spsoft.vatoutinv.entity.vmscreditlimit.VmsCreditLimit;
import com.spsoft.vatoutinv.entity.vmsfullbswjmanager.VmsFullBswjManager;
import com.spsoft.vatoutinv.enums.CommonEnum;
import com.spsoft.vatoutinv.service.vmscreditlimit.VmsCreditLimitService;
import com.spsoft.vatoutinv.service.vmsfullbswjmanager.VmsFullBswjManagerService;
import com.spsoft.vms.redis.service.BswjRedisService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 授信额度月初自动下载定时任务
 * 下载额度与上月月末 已下载未使用 额度保持一致
 * 同一个月内不可重复执行！！！否则每执行一次，已下载未使用额度就会翻倍一次！！！
 *
 * @author : chenxudong
 * @date : 2024/6/13 13:34
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class VmsCreditLimitDownloadJob {

    public static final String LOG_MSG = "(授信额度自动下载定时任务)";

    private final VmsFullBswjManagerService vmsFullBswjManagerService;

    private final VmsCreditLimitService vmsCreditLimitService;

    private final BswjRedisService bswjRedisService;

    /**
     * 直连单位ID
     */
    @Value("${leqi.zldwId}")
    private String zldwId;

    @XxlJob("vmsCreditLimitDownloadJobHandler")
    public ReturnT<String> VmsCreditLimitDownloadJobHandler() {
        long start = System.currentTimeMillis();
        XxlJobHelper.log("{}开始执行，traceId：{}", LOG_MSG, MDC.get("traceId"));

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        XxlJobHelper.log("{}分片参数，当前分片序号：{}, 总分片数：{}", LOG_MSG, shardIndex, shardTotal);

        // 获取接入数电的机构配置信息
        List<VmsFullBswjManager> sdDeptInfoList = vmsFullBswjManagerService.getAllSdDeptInfo();
        boolean success = true;
        if (CollectionUtil.isNotEmpty(sdDeptInfoList)) {
            for (int i = 0; i < sdDeptInfoList.size(); i++) {
                try {
                    if (i % shardTotal != shardIndex) {
                        XxlJobHelper.log("{}第{}次循环，未命中分片，不做处理", LOG_MSG, i + 1);
                        continue;
                    }
                    VmsFullBswjManager bswjManager = sdDeptInfoList.get(i);
                    XxlJobHelper.log("{}第{}次循环，机构编码：{}，纳税人名称：{}，纳税人识别号：{}",
                            LOG_MSG, i + 1, bswjManager.getWhjg(), bswjManager.getNsztName(), bswjManager.getNsrsbh());
                    // 获取本地授信额度信息
                    LambdaQueryWrapper<VmsCreditLimit> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(VmsCreditLimit::getDeptCode, bswjManager.getWhjg());
                    VmsCreditLimit localCreditLimit = vmsCreditLimitService.getOne(queryWrapper);
                    XxlJobHelper.log("{}查询出本地授信额度：{}", LOG_MSG, JSONObject.toJSONString(localCreditLimit));

                    // 先查询乐企授信额度
                    TokenUser tokenUser = new TokenUser();
                    tokenUser.setDeptCode(bswjManager.getWhjg());
                    tokenUser.setUserCode("定时任务");
                    tokenUser.setUserName("定时任务");
                    BaseNsrRequestParams params = new QueryClassifyCodeParams();
                    params.setNsrsbh(bswjManager.getNsrsbh());
                    params.setCreateUser(tokenUser.getUserCode());
                    params.setDeptCode(tokenUser.getDeptCode());
                    Result<Object> result = vmsCreditLimitService.getCreditLimitByLq(params, tokenUser);
                    if (ResponseEnum.SUCCESS_MSG.getCode().equals(result.getCode())) {
                        XxlJobHelper.log("{}查询授信额度成功", LOG_MSG);
                        if (localCreditLimit != null && localCreditLimit.getYxzwsyed().compareTo(BigDecimal.ZERO) > 0) {
                            // 查询乐企授信额度成功，上月已下载未使用额度大于0，调用乐企接口下载授信额度
                            String sydwbh = bswjRedisService.getSydwbh(tokenUser.getDeptCode());
                            ApplyCreditParams param = new ApplyCreditParams();
                            param.setPtbh(sydwbh);
                            param.setYwlsh(sydwbh + zldwId + RandomUtil.randomString(32));
                            param.setSqlx(CommonEnum.CREDIT_LIMIT_APPLY_TYPE_0.getKey());
                            param.setSqed(localCreditLimit.getYxzwsyed());
                            param.setNsrsbh(bswjManager.getNsrsbh());
                            param.setCreateUser(tokenUser.getUserCode());
                            param.setDeptCode(tokenUser.getDeptCode());
                            Result<Object> dmzResult = vmsCreditLimitService.applyCreditLimitByLq(param, tokenUser);
                            if (ResponseEnum.SUCCESS.getCode().equals(dmzResult.getCode())) {
                                XxlJobHelper.log("{}下载授信额度成功", LOG_MSG);
                            } else {
                                XxlJobHelper.log("{}下载授信额度失败，错误信息：{}", LOG_MSG, dmzResult.getMessage());
                                success = false;
                            }
                        } else {
                            XxlJobHelper.log("{}已下载未使用额度<=0，不进行授信额度下载", LOG_MSG);
                        }
                    } else {
                        XxlJobHelper.log("{}查询授信额度失败，错误信息：{}", LOG_MSG, result.getMessage());
                        success = false;
                    }
                } catch (Exception e) {
                    XxlJobHelper.log("{}下载授信额度失败，错误信息：{}", LOG_MSG, e.getMessage());
                    success = false;
                }
            }
        }

        long end = System.currentTimeMillis();
        XxlJobHelper.log("{}执行完成，用时：{}ms", LOG_MSG, end - start);
        if (success) {
            return ReturnT.SUCCESS;
        } else {
            XxlJobHelper.handleFail();
            return ReturnT.FAIL;
        }
    }
}
